package sessionBean;

import entity.InsertItem;
import entity.ShortQResponse;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
@LocalBean
public class ShortQSessionBean {

    @PersistenceContext
    private EntityManager em;

    public boolean addQuestion(int id, String question, String type) {
        try {
           if(em.find(InsertItem.class, id)!=null) return false;
            InsertItem qItem = new InsertItem();
            qItem.setId(id); 
            qItem.setQuestion(question);
            qItem.setType(type);
            em.persist(qItem);
            em.flush();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public List<InsertItem> getAllQuestions() {
        String qryStr = "SELECT i FROM InsertItem i";
        Query query = em.createQuery(qryStr);
        return query.getResultList();
    }
    
    public List<InsertItem> getAllGeneralQuestions(){
        String qryStr = "SELECT i FROM InsertItem i WHERE i.type = :Type";
        Query query = em.createQuery(qryStr);
        query.setParameter("Type", "general");
        return query.getResultList();
    }
    
    public List<InsertItem> getAllEstimateQuestions(){
        String qryStr = "SELECT i FROM InsertItem i WHERE i.type = :Type";
        Query query = em.createQuery(qryStr);
        query.setParameter("Type", "estimate");
        return query.getResultList();
    }

    public boolean editQuestion(int qid, String newQuestion, String type) {
        try {
            InsertItem qItem = em.find(InsertItem.class, qid);
            qItem.setQuestion(newQuestion);
            qItem.setType(type);
            em.merge(qItem);
            em.flush();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean deleteQuestion(int qid) {
        try {
            InsertItem qItem = em.find(InsertItem.class, qid);
            for (ShortQResponse s : qItem.getAnswer()) {
                s.setQuestion(null);
                em.merge(s);
            }
            em.remove(qItem);
            em.flush();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
